﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AGR.Model;
using AGR.Services;
using AGR.Services.Course;
using AGR.Services.Course.Contract;

namespace AGR.Web.Pages.Courses
{
    public partial class Subjects : System.Web.UI.Page
    {
        private ISubjectService _subjectService = new SubjectService();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                this.ClearMessage();
                this.LoadGrid();
            }
        }

        #region Button Methods

        protected void btnSearchSubject_Click(object sender, EventArgs e)
        {
            string searchBy = txtSearchSubject.Text;

            if (string.IsNullOrEmpty(searchBy))
            {
                this.ShowMessage("Please enter a search parameter and try again.", SiteMaster.MessageType.Information);
                txtSearchSubject.Focus();
                return;
            }

            this.ClearMessage();

            var result = _subjectService.GetAllSubjects(x => x.SubjectCode == searchBy ||
                                                           x.Title.Contains(searchBy) ||
                                                           x.Type.Contains(searchBy) ||
                                                           x.Description.Contains(searchBy) ||
                                                           x.NQFLevel == int.Parse(searchBy) ||
                                                           x.Credits == int.Parse(searchBy));

            this.LoadGrid(result);
        }

        protected void btnSearchClear_Click(object sender, EventArgs e)
        {
            this.ClearMessage();
            txtSearchSubject.Text = string.Empty;
            this.LoadGrid();
        }

        protected void btnAddSubject_Click(object sender, EventArgs e)
        {
            SubjectGridView.ShowFooter = true;
            SubjectGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void btnSubjectDelete_Click(object sender, EventArgs e)
        {
            bool selected = false;
            int selectCount = 0;
            int deleteCount = 0;
            string succesMessages = string.Empty;
            string errorMessages = string.Empty;

            IList<ActionResult> results = new List<ActionResult>();

            for (int i = 0; i < SubjectGridView.Rows.Count; i++)
            {
                var row = SubjectGridView.Rows[i];
                bool isChecked = ((CheckBox)row.FindControl("chkSelect")).Checked;

                if (isChecked)
                {
                    // TODO: Check relationships before delete

                    string code = (string)this.SubjectGridView.DataKeys[i].Value;
                    results.Add(_subjectService.DeleteSubject(code));
                    selected = true;
                    selectCount++;
                }
            }

            if (selected == false)
            {
                this.ShowMessage("Please select records for deletion and try again.", SiteMaster.MessageType.Information);
                return;
            }

            foreach (ActionResult result in results)
            {
                if (result.Success)
                {
                    succesMessages = result.Message;
                    deleteCount++;
                }
                else
                    errorMessages = result.Message;
            }

            if (!string.IsNullOrEmpty(succesMessages))
                this.ShowMessage(succesMessages, SiteMaster.MessageType.Success);

            if (!string.IsNullOrEmpty(errorMessages))
                this.ShowMessage(errorMessages + " " + (selectCount - deleteCount) + " record(s) was not deleted.", SiteMaster.MessageType.Error);

            SubjectGridView.EditIndex = -1;

            this.LoadGrid();
        }

        protected void btnSubjectDetailsClose_Click(object sender, EventArgs e)
        {
            //CourseDetailModalPopupExtender.Hide();
        }

        #endregion

        #region GridView Methods

        protected void SubjectGridView_OnRowCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Insert")
            {
                string code = ((TextBox)SubjectGridView.FooterRow.FindControl("txtSubjectCode")).Text.ToString();

                var exists = _subjectService.GetSubject(code);

                if (exists != null)
                {
                    this.ShowMessage("Your action could not be completed. A record with subject code (" + code + ") already exists on the system.", SiteMaster.MessageType.Warning);
                    return;
                }

                var entity = new Subject
                {
                    SubjectCode = code,
                    Type = ((TextBox)SubjectGridView.FooterRow.FindControl("txtType")).Text.ToString(),
                    Title = ((TextBox)SubjectGridView.FooterRow.FindControl("txtTitle")).Text.ToString(),
                    Description = ((TextBox)SubjectGridView.FooterRow.FindControl("txtDescription")).Text.ToString(),
                    NQFLevel = int.Parse(((TextBox)SubjectGridView.FooterRow.FindControl("txtNQFLevel")).Text),
                    Credits = int.Parse(((TextBox)SubjectGridView.FooterRow.FindControl("txtCredits")).Text),
                    UserCreated = "TestUser"
                };

                var result = _subjectService.AddSubject(entity);

                if (result.Success)
                {
                    this.ShowMessage(result.Message, SiteMaster.MessageType.Success);
                    SubjectGridView.ShowFooter = false;
                    SubjectGridView.EditIndex = -1;
                    this.LoadGrid();
                }
                else
                    this.ShowMessage(result.Message, SiteMaster.MessageType.Error);
            }
            else if (e.CommandName == "CancelInsert")
            {
                this.ClearMessage();
                SubjectGridView.ShowFooter = false;
                SubjectGridView.EditIndex = -1;
                this.LoadGrid();
            }
        }

        protected void SubjectGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            string code = ((TextBox)SubjectGridView.Rows[e.RowIndex].FindControl("txtSubjectCode")).Text.ToString();

            var entity = _subjectService.GetSubject(x => x.SubjectCode == code);

            entity.SubjectCode = code;
            entity.Type = ((TextBox)SubjectGridView.Rows[e.RowIndex].FindControl("txtType")).Text.ToString();
            entity.Title = ((TextBox)SubjectGridView.Rows[e.RowIndex].FindControl("txtTitle")).Text.ToString();
            entity.Description = ((TextBox)SubjectGridView.Rows[e.RowIndex].FindControl("txtDescription")).Text.ToString();
            entity.NQFLevel = int.Parse(((TextBox)SubjectGridView.Rows[e.RowIndex].FindControl("txtNQFLevel")).Text);
            entity.Credits = int.Parse(((TextBox)SubjectGridView.Rows[e.RowIndex].FindControl("txtCredits")).Text);
            entity.UserModified = "TestUser";

            var result = _subjectService.UpdateSubject(entity);

            if (result.Success)
            {
                this.ShowMessage(result.Message, SiteMaster.MessageType.Success);
                SubjectGridView.EditIndex = -1;
                this.LoadGrid();
            }
            else
                this.ShowMessage(result.Message, SiteMaster.MessageType.Error);
        }

        protected void SubjectGridView_RowEditing(object sender, GridViewEditEventArgs e)
        {
            this.ClearMessage();
            SubjectGridView.ShowFooter = false;
            SubjectGridView.EditIndex = e.NewEditIndex;
            this.LoadGrid();
        }

        protected void SubjectGridView_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
        {
            SubjectGridView.EditIndex = -1;
            this.LoadGrid();
        }

        protected void SubjectGridView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            SubjectGridView.PageIndex = e.NewPageIndex;
            SubjectGridView.EditIndex = -1;
            this.LoadGrid();
        }

        #endregion

        #region Private Methods

        private void LoadGrid()
        {
            var subjects = _subjectService.GetAllSubjects();

            if (subjects.Count == 0)
            {
                subjects.Add(new Subject());
                SubjectGridView.ShowFooter = true;
                SubjectGridView.EditIndex = -1;

                SubjectGridView.DataSource = subjects;
                SubjectGridView.DataBind();
                SubjectGridView.Rows[0].Visible = false;
            }
            else
            {
                SubjectGridView.DataSource = _subjectService.GetAllSubjects();
                SubjectGridView.DataBind();
            }
        }

        private void LoadGrid(IList<Subject> subjects)
        {
            SubjectGridView.DataSource = subjects;
            SubjectGridView.DataBind();
        }

        private void ShowMessage(string message, AGR.Web.SiteMaster.MessageType messagetype)
        {
            var master = (SiteMaster)Page.Master;
            master.ShowMessage(message, messagetype);
        }

        private void ClearMessage()
        {
            var master = (SiteMaster)Page.Master;
            master.ClearMessage();
        }

        #endregion
    }
}